﻿using Models;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using Web.Areas.Mobile.Lib;
using Web.Lib;

namespace Web.Areas.Mobile.Controllers
{
    public class UserController : BaseController
    {
        public ActionResult LogOut()
        {
            MobileAccount.LogOut();
            return View("SystemError");
        }
        /// <summary>
        /// 服务号授权
        /// </summary>
        public ActionResult Auth(string openid, string redirectUrl)
        {
            var queryParams = GenerateQuerString();

            if (string.IsNullOrWhiteSpace(redirectUrl))
            {
                redirectUrl = "/mobile/survey/mark";
            }
            if (MobileAccount.ID > 0)
            {
                return Redirect(GenerateUrl(redirectUrl.Replace("_", "/"), queryParams));
            }

            if (!string.IsNullOrWhiteSpace(openid))
            {
                //保存至浏览器cookie
                new MobileAccount().LogOn(openid);
                return Redirect(GenerateUrl(redirectUrl.Replace("_", "/"), queryParams));
            }

            string appid, appsecret;
            new Admin.Lib.Site().GetAppConfig(out appid, out appsecret);

            var redirectUri = eDoctor.SDK.WeChat.WebPage.Call.authorize(appid, Common.UrlHelper.HostUrl + "/mobile/user/oauth?" + queryParams, "QAZEDCTGB");

            Logs.Execute("redirectUri：" + redirectUri);
            if (!string.IsNullOrWhiteSpace(redirectUri))
            {
                return Redirect(redirectUri);
            }
            else
            {
                return Redirect("/mobile/survey/notopen?msg=无法获取您的用户信息！");
            }
        }

        private string GenerateUrl(string url, string queryParams)
        {
            return url + (url.IndexOf("?") < 0 ? "?" : "&") + queryParams;
        }

        private string GenerateUrl(string url, List<string> queryParams)
        {
            return url + (url.IndexOf("?") < 0 ? "?" : "&") + string.Join("&", queryParams);
        }

        private string GenerateQuerString()
        {
            var queryParams = new List<string>();
            var qs = Request.QueryString;
            if (qs.HasKeys())
            {
                foreach (string ck in qs.Keys)
                {
                    if (ck.ToLower() != "openid".ToLower())
                    {
                        queryParams.Add(ck + "=" + qs[ck]);
                    }
                }
            }
            return string.Join("&", queryParams);
        }

        /// <summary>
        /// 授权回调
        /// </summary>
        /// <returns></returns>
        public ActionResult OAuth(string code, string state, string redirectUrl)
        {
            wx_usersLogic ul = new wx_usersLogic();
            string appid, appsecret;
            if (new Admin.Lib.Site().GetAppConfig(out appid, out appsecret))
            {
                //通过code换取网页授权access_token
                var webtoken = eDoctor.SDK.WeChat.WebPage.Call.access_token(appid, appsecret, code);
                //Logs.Execute("webtoken:" + Common.JsonHelper.JsonSerializer(webtoken));
                //判断授权是否成功
                if (webtoken == null || string.IsNullOrEmpty(webtoken.openid))
                {
                    return Redirect("/mobile/survey/notopen?msg=无法获取您的用户信息！");
                }
                var filePath = "/upload/avatars/";
                var fileName = webtoken.openid + ".jpg";
                var access_token = new Admin.Lib.Site().GetAccessToken();
                //判断是否已经获取过用户信息
                var dbWuser = ul.Getwx_users(new wx_users { openid = webtoken.openid });
                if (dbWuser == null)
                {
                    wx_users newUser = new wx_users { createdate = DateTime.Now, openid = webtoken.openid };
                    var u = new eDoctor.SDK.WeChat.Call(access_token).GetUserInfo(webtoken.openid, false);
                    //Logs.Execute("u:" + Common.JsonHelper.JsonSerializer(u));
                    if (u.errcode != 0)
                    {
                        return Redirect("/mobile/survey/notopen?msg=无法获取您的用户信息！");
                    }
                    else
                    {
                        var httpUrl = u.headimgurl;

                        if (this.DownLoad(httpUrl.Replace("/0", "/132"), System.Configuration.ConfigurationManager.AppSettings["SitePath"] + filePath, fileName))
                        {
                            newUser.headimgurl = filePath + fileName;
                        }
                        else
                        {
                            return Redirect("/mobile/survey/notopen?msg=无法获取您的用户信息！");
                        }
                        newUser.nickname = u.nickname;
                        newUser.city = u.city;
                        newUser.country = u.country;
                        newUser.province = u.province;
                        newUser.language = u.language;
                    }
                    var result = ul.Add(newUser);
                    if (!result)
                    {
                        return Redirect("/mobile/survey/notopen?msg=无法获取您的用户信息！");
                    }
                }
                //保存至浏览器cookie
                var r = new MobileAccount().LogOn(webtoken.openid);

                if (string.IsNullOrWhiteSpace(redirectUrl))
                {
                    redirectUrl = "/mobile/survey/mark";
                }

                //自带参数
                var querystring = string.Empty;
                foreach (string key in Request.QueryString.Keys)
                {
                    if (key != "code" && key != "state" && key.ToLower() != "redirecturl")
                    {
                        querystring += "&" + key + "=" + Request.QueryString[key];
                    }
                }
                return Redirect(redirectUrl.Replace("_", "/") + (redirectUrl.IndexOf("?") < 0 ? "?" : "&") + querystring);
            }
            else
            {
                return Redirect("/mobile/survey/notopen?msg=无法获取您的用户信息！");
            }
        }

        /// <summary>
        /// 下载文件
        /// </summary>
        internal Boolean DownLoad(string httpUrl, string filePath, string fileName)
        {
            try
            {
                filePath = filePath.Replace("/", @"\");
                //创建目录
                Common.FileHelper.CreateFolder(filePath);
                //下载头像到本地
                using (System.Net.WebClient client = new System.Net.WebClient())
                {
                    client.DownloadFile(httpUrl, filePath + fileName);
                }
                return true;
            }
            catch (Exception ex)
            {
                return false;
            }
        }
    }
}
